//package com.dream.service.recommender.hub.rec;
//
//import com.dream.common.model.response.BaseListResponse;
//import com.dream.common.model.response.BaseResponse;
//import com.dream.common.model.response.ErrorCode;
//import com.dream.service.procure.domain.enums.StockStatus;
//import com.dream.service.product.domain.entity.SpuBase;
//import com.dream.service.recommender.base.compare.WeightComparator;
//import com.dream.service.recommender.base.impl.BaseRecommenderService;
//import com.dream.service.recommender.domain.request.BaseRequest;
//import com.dream.service.recommender.domain.request.FrontParam;
//import com.dream.service.recommender.domain.response.RecommenderData;
//import com.dream.service.recommender.domain.response.RecommenderItem;
//import com.dream.service.recommender.domain.response.RecommenderSku;
//import com.dream.service.recommender.hub.util.CacheUtil;
//import com.dream.service.recommender.hub.util.ParamUtil;
//import com.dream.service.recommender.toolkits.cache.RedisCache;
//import com.dream.service.recommender.toolkits.utils.ConfigUtil;
//import com.dream.service.recommender.toolkits.utils.StringUtils;
//import com.dream.service.search.api.SearchRecallService;
//import com.dream.service.search.domain.entity.ProductRecallResult;
//import com.dream.service.search.domain.request.ProductSearchRequest;
//import com.dream.service.topic.api.erp.FeedService;
//import com.dream.service.wrapper.domain.entity.SPUData;
//import org.apache.log4j.Logger;
//import org.springframework.beans.factory.annotation.Autowired;
//
//import java.util.*;
//
///**
// * Daily
// * Created by duxy on 2016/04/25.
// */
//public class DailyFillListRecommender extends BaseRecommenderService {
//
//    private Logger logger = Logger.getLogger(DailyFillListRecommender.class);
//
//
//    public static SearchRecallService searchRecallService;
//
//    public SearchRecallService getSearchRecallService() {
//        return searchRecallService;
//    }
//
//    @Autowired
//    public void setSearchRecallService(SearchRecallService searchRecallService) {
//        this.searchRecallService = searchRecallService;
//    }
//
//
//    public FeedService getFeedService() {
//        return feedService;
//    }
//
//    @Autowired
//    public void setFeedService(FeedService feedService) {
//        this.feedService = feedService;
//    }
//
//    public TopicXmlService getTopicXmlService() {
//        return topicXmlService;
//    }
//
//    @Autowired
//    public void setTopicXmlService(TopicXmlService topicXmlService) {
//        this.topicXmlService = topicXmlService;
//    }
//
//    private static FeedService feedService;
//    private static TopicXmlService topicXmlService;
//
//
//    // 获取商品数据倍数
//    private int multiple = 5;
//
//    // 失效时间间隔 (sec)
//    private int residue_time_interval = Integer.parseInt(ConfigUtil.getPro("residue_time_interval_df"));
//
//    // 缓存
//    private final String cacheKey = "rec_dailyfill_list_";
//
//    // 缓存
//    private RedisCache redisCache = RedisCache.getInstance();
//
//    @Override
//    public BaseResponse<RecommenderData> getRecommender(BaseRequest<FrontParam> frontParamBaseRequest) {
//        long sTime = System.currentTimeMillis();
//        BaseResponse<RecommenderData> recommenderResponse = new BaseResponse<RecommenderData>();
//        try {
//            if (frontParamBaseRequest == null || frontParamBaseRequest.getParam() == null || frontParamBaseRequest.getParam().getUser() == null) {
//                return buildResult(recommenderResponse, false, ErrorCode.PARAM_ERROR.getCode(), ErrorCode.PARAM_ERROR.getError_msg(), null);
//            }
//            FrontParam frontParam = frontParamBaseRequest.getParam();
//            int cid = ParamUtil.getCid(frontParam);
//            int pagesize = ParamUtil.getPageSize(frontParam);
//            int page = ParamUtil.getPage(frontParam);
//            Map<Integer, Double> categoryWeightMap = new HashMap<Integer, Double>();
//            if (cid > 0) {
//                categoryWeightMap.put(cid, 1d);
//            }
//            /*int skip = pagesize * (page - 1);*/
//            //已经展示sku集合
//            String pin = ParamUtil.getPin(frontParam);
//            String uuid = ParamUtil.getUUid(frontParam);
//            Set<Long> existSpus = gatherExistSpuInfo(pin, uuid, cid, page, pagesize);
//            List<ProductRecallResult> recallResults = gatherSearchRecallData(categoryWeightMap, null, pagesize * multiple, existSpus, 0);
//
//            RecommenderData recommenderData = buildResult(recallResults, cid);
//            recommenderResponse = buildResult(recommenderResponse, true, ErrorCode.OK.getCode(), "", recommenderData, 0, pagesize);
//
//            Set<Long> spus = rebuildPositionInfo(recommenderResponse.getResult());
//            backupExistSpuInfo(pin, uuid, spus, cid);
//            long usedTime = System.currentTimeMillis() - sTime;
//            recommenderData.setLatency(usedTime);
//            recommenderResponse.setLatency(usedTime);
//            return recommenderResponse;
//        } catch (Exception e) {
//            logger.error("daily===>getRecommender:::", e);
//            return buildResult(recommenderResponse, false, ErrorCode.PROCESS_ERROR.getCode(), e.getMessage(), null);
//        }
//    }
//
//    public Set<Long> gatherExistSpuInfo(String pin, String uuid, int category, int pageNum, int pageSize) {
//        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) {
//            return Collections.emptySet();
//        }
//        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
//        String key = cacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
//        if (pageNum == 1) {
//            redisCache.delKey(key.getBytes());
//            return Collections.emptySet();
//        }
//        Set<Long> spus = CacheUtil.getExistSpus(redisCache, key, (pageNum - 1) * pageSize);
//        if (spus == null) {
//            return Collections.emptySet();
//        }
//        return spus;
//    }
//
//
//    protected List<ProductRecallResult> gatherSearchRecallData(Map<Integer, Double> categoryWeightMap, Map<Integer, Double> labelWeightMap, int limit, Set<Long> existSpus, int skip) {
//        ProductSearchRequest request = new ProductSearchRequest();
//
//        if (categoryWeightMap != null && !categoryWeightMap.isEmpty()) {
//            request.setFrontCategoryWeightMap(categoryWeightMap);
//        }
//        if (labelWeightMap != null && !labelWeightMap.isEmpty()) {
//            request.setLabelWeightMap(labelWeightMap);
//        }
//        request.setDaily(true);///////////daily页面的请求
//        request.setLimit(limit);
//        request.setSkip(skip);
//        if (existSpus != null && !existSpus.isEmpty()) {
//            request.setExistKeys(existSpus);
//        }
//
//        try {
//            if (searchRecallService == null) {
//                return null;
//            }
//            BaseResponse<List<ProductRecallResult>> recallResponse = searchRecallService.productSearchRecall(request);
//            if (recallResponse.isSuccess()) {
//                return recallResponse.getResult();
//            }
//        } catch (Exception e) {
//            logger.error("daily===>gatherSearchRecallData:::", e);
//
//        }
//        return null;
//    }
//
//    /**
//     * 更新位置信息
//     *
//     * @param recommenderData
//     * @return
//     */
//    public Set<Long> rebuildPositionInfo(RecommenderData recommenderData) {
//        if (recommenderData == null || StringUtils.isEmpty(recommenderData.getList())) {
//            return null;
//        }
//        List<RecommenderItem> items = recommenderData.getList();
//        Set<Long> spus = new HashSet<Long>();
//        int pos = 1;
//        for (RecommenderItem recommenderItem : items) {
//            recommenderItem.setPos(pos++);
//            if (recommenderItem instanceof RecommenderSku) {
//                try {
//                    spus.add(((RecommenderSku) recommenderItem).getSpu());
//                } catch (Exception e) {
//                    logger.error("product detail===>rebuildPositionInfo:::", e);
//
//                }
//            }
//        }
//        return spus;
//    }
//
//    public void backupExistSpuInfo(String pin, String uuid, Set<Long> spus, int category) {
//        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) return;
//        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
//        String key = cacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
//        List<Long> cache = CacheUtil.backupCache(redisCache, key, spus, residue_time_interval, -1);
//        System.out.println("Backup Exist Spu :" + (cache == null ? "" : Arrays.toString(cache.toArray())));
//    }
//
//    /**
//     * 封装结果
//     *
//     * @param recallResults
//     * @param category
//     * @return
//     */
//    private RecommenderData buildResult(List<ProductRecallResult> recallResults, int category) {
//        if (StringUtils.isEmpty(recallResults)) {
//            return new RecommenderData();
//        }
//        RecommenderData<RecommenderSku> recommenderData = new RecommenderData<RecommenderSku>();
//        List<RecommenderSku> recommenderSkus = new ArrayList<RecommenderSku>();
//        recommenderData.setList(recommenderSkus);
//        Set<Long> spus = new HashSet<Long>();
//        for (ProductRecallResult recallResult : recallResults) {
//            spus.add(recallResult.getSpu());
//        }
//        Map<Long, SPUData> spuDataMap = getBaseInfo(spus);
//        if (spuDataMap == null || spuDataMap.isEmpty()) {
//            return recommenderData;
//        }
//        for (ProductRecallResult recallResult : recallResults) {
//            RecommenderSku recommenderSku = buildProduct(recallResult, spuDataMap.get(recallResult.getSpu()));
//            if (recommenderSku != null) {
//                recommenderSkus.add(recommenderSku);
//            }
//        }
//        BaseListResponse baseListResponse = feedService.listActiveFeedTopic();
////        Set<Long> ids = (Set<Long>) baseListResponse.getResult().getList();
////        BaseListResponse spuList = topicXmlService.getSpuByTopics(ids);
//        Set<Long> topicSpus = (Set<Long>) topicXmlService.getSpuByTopics((Set<Long>) baseListResponse.getResult().getList()).getResult().getList();
////        System.out.println(topicSpus);
//        SortAndRankBoostTopic(recommenderData, topicSpus, spuDataMap);
//        return recommenderData;
//    }
//
//    /**
//     * 封装商品信息
//     *
//     * @param recallResult
//     * @param spuData
//     * @return
//     */
//    protected RecommenderSku buildProduct(ProductRecallResult recallResult, SPUData spuData) {
//        if (recallResult == null || recallResult.getModel_image_path() == null || recallResult.getModel_image_path().length() == 0 || spuData == null || spuData.getSpuBase() == null || spuData.getStockStatus() == StockStatus.NO || spuData.getSpuBase().getIsPutOn() == 0) {
//            return null;
//        }//如果没有模特合成图抛弃该商品
//
//        RecommenderSku recommenderSku = new RecommenderSku();
//        SpuBase spuBase = spuData.getSpuBase();
//        recommenderSku.setSpu(spuBase.getSpu());
//        recommenderSku.setSale_type(spuBase.getSale_type());
//        recommenderSku.setMain_sku(spuBase.getMain_sku());
//        recommenderSku.setMain_title(spuBase.getMain_title());
//        recommenderSku.setW(recallResult.getQuality_score());
//        recommenderSku.setSub_title(recallResult.getSub_title());
//        recommenderSku.setMain_image_url(recallResult.getModel_image_path());//把模特合成图赋给主图
//        recommenderSku.setCid3(recallResult.getCid3());
//        if (recallResult !=null && recallResult.getOther_image_paths() != null) {
//            recommenderSku.setImage_paths(recallResult.getOther_image_paths());
//        }
//        if (recallResult.getFront_cids() != null && recallResult.getFront_cids().size() > 0)
//            recommenderSku.setFront_category_id(recallResult.getFront_cids().get(0));//只取得一个，不知道会不会有问题
//        if (spuData.getSkuPrice() != null) {
//            recommenderSku.setSkuPrice(spuData.getSkuPrice());
//        } else {
//            return null;
//        }
//        return recommenderSku;
//    }
//
//
//    public RecommenderData SortAndRankBoostTopic(RecommenderData recommenderData, Set<Long> topicSpus, Map<Long, SPUData> spuDataMap) {
//        if (recommenderData == null) {
//            return recommenderData;
//        }
//        List<RecommenderSku> recommenderSkus = recommenderData.getList();
//        if (StringUtils.isEmpty(recommenderSkus)) {
//            return recommenderData;
//        }
//        Map<Integer, List<RecommenderSku>> categoryItems = new HashMap<Integer, List<RecommenderSku>>();
//        for (RecommenderSku recommenderSku : recommenderSkus) {//根据cid重组所有spu
//            long spu = recommenderSku.getSpu();
//            SPUData spuData = spuDataMap.get(spu);
//            if (spuData == null) {
//                continue;
//            }
//            SpuBase spuBase = spuData.getSpuBase();
////            List<RecommenderSku> relSkus = categoryItems.get(spuBase.getCategory_id());
////            System.out.println(recommenderSku.getFront_category_id());
//            List<RecommenderSku> relSkus = categoryItems.get(recommenderSku.getFront_category_id());
//            if (relSkus == null) {
//                relSkus = new ArrayList<RecommenderSku>();
//                categoryItems.put(recommenderSku.getCid3(), relSkus);
////                System.out.println(recommenderSku.getCid3());
//            }
//            relSkus.add(recommenderSku);
//        }
//        List<RecommenderSku> sortRecommenderItems = new ArrayList<RecommenderSku>();
//        boolean loop = true;
//        do {
////            System.out.println("loop: 0");
//            List<RecommenderSku> subRecommenderItems = new ArrayList<RecommenderSku>(categoryItems.size());
////            System.out.println("cid size:"+categoryItems.size());
//            Iterator<Map.Entry<Integer, List<RecommenderSku>>> entryiterator = categoryItems.entrySet().iterator();
//            while (entryiterator.hasNext()) {
////                System.out.println("while: 0");
//                Map.Entry<Integer, List<RecommenderSku>> productentry = entryiterator.next();
//                List<RecommenderSku> productList = productentry.getValue();
//                if (StringUtils.isEmpty(productList)) {
//                    entryiterator.remove();
//                    continue;
//                }
//                RecommenderSku recommenderSku = productList.remove(0);
//                recommenderSku.setW(Math.random() * 1);
//                if (topicSpus.contains(recommenderSku.getSpu()))//给daily页面的topic中包含的商品增加0.7的权重
//                {
////                    System.out.println("spu:" + recommenderSku.getSpu());
////                    System.out.println(recommenderSku.getW() + 0.7);
//                    recommenderSku.setW(recommenderSku.getW() + 0.7);
//                }
//                subRecommenderItems.add(recommenderSku);
//            }
//
//            sortRecommenderItems.addAll(subRecommenderItems);
//            if (categoryItems.isEmpty()) {
//                loop = false;
//            }
//            if (categoryItems.size() == 1) {
//                Set<Integer> keys = categoryItems.keySet();
//                Iterator<Integer> keyiterator = keys.iterator();
//                while (keyiterator.hasNext()) {
//                    Integer catid = keyiterator.next();
//                    sortRecommenderItems.addAll(categoryItems.get(catid));
//                }
//                loop = false;
//            }
//        } while (loop);
//        Collections.sort(sortRecommenderItems, new WeightComparator());
//        recommenderData.setList(sortRecommenderItems);
//        return recommenderData;
//    }
//
//
//}
